/**
 * Copyright 2011 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.appengine.codelab;

import java.io.IOException;
import java.io.PrintWriter;
//import java.util.HashSet;
//import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.Entity;
//import com.google.appengine.api.datastore.Key;
//import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.codelab.Util;

/**
 * This servlet responds to the request corresponding to midias. The servlet
 * manages the Midia Entity
 * 
 * @author
 */
@SuppressWarnings("serial")
public class MidiaServlet extends BaseServlet {

  private static final Logger logger = Logger.getLogger(MidiaServlet.class.getCanonicalName());

  /**
   * Get the entities in JSON format.
  */
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
	  	super.doGet(req,resp);
	    logger.log(Level.INFO, "Obtaining Lidia listing");
	    String searchBy = req.getParameter("midia-searchby");
	    String searchFor = req.getParameter("q");
	    PrintWriter out = resp.getWriter();
	    if (searchFor == null || searchFor.equals("")) {
	      Iterable<Entity> entities = Midia.getAllMidia();
	      out.println(Util.writeJSON(entities));
	    } else if (searchBy == null || searchBy.equals("midia_id")) {
	      Iterable<Entity> entities = Midia.getMidia(searchFor);
	      out.println(Util.writeJSON(entities));
	    } 
	  }
	/**
	 * Create the entity and persist it.
	 */
  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
	  throws ServletException, IOException {
	logger.log(Level.INFO, "Creating Midia");
    PrintWriter out = resp.getWriter();
    String midia_id = req.getParameter("midia_id");
    String midia_name = req.getParameter("midia_name");
    String midia_description = req.getParameter("midia_description");
    String midia_number = req.getParameter("midia_number");
    String midia_bandeira = req.getParameter("midia_bandeira");
    String cliente_id = req.getParameter("cliente_id");
        
    try {
      Midia.createOrUpdateMidia(midia_id, midia_name, midia_description, midia_number, midia_bandeira, cliente_id);
    } catch (Exception e) {
      String msg = Util.getErrorResponse(e);
      out.print(msg);
    }
  }

	/**
	 * Delete the midia. Gives an error when we try to delete the midia that has items
	 * associated with it
	 */
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
	  	super.doGet(req, resp);
	  	logger.log(Level.INFO, "Deleting Midia");
	    String midiaKey = req.getParameter("id");
	    PrintWriter out = resp.getWriter();
	    Iterable<Entity> entities = Util.listEntities("Midia", "midia_id", midiaKey);
	    try {	     
	      Entity e = Midia.getSingleMidia(midiaKey);
	      Util.deleteFromCache(e.getKey());
	      Util.deleteEntity(e.getKey());
	      out.print("Midia deleted successfully.");
	    } catch (Exception e) {
	      String msg = Util.getErrorResponse(e);
	      out.print(msg);
	    }
	  }

	/**
	 * Redirect the call to doDelete or doPut method
	 */
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    String action = req.getParameter("action");
    if (action.equalsIgnoreCase("delete")) {
      doDelete(req, resp);
	  return;
    } else if (action.equalsIgnoreCase("put")) {
	  doPut(req, resp);
      return;
    }
  }
}